//
//  LoginViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/8.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController {
    
    override var shouldAutorotate: Bool {
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    private var nextStepEnable: Bool {
        return !UserDefaults.account.isEmpty || !UserDefaults.password.isEmpty
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(endEditing))
        view.addGestureRecognizer(tap)
        
        let backBtn = UIBarButtonItem(imageName: "nav_back", target: self, action: #selector(back))
        navigationItem.leftBarButtonItem = backBtn
        
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(hex: "#E2ECFF").cgColor, UIColor(red: 246/255.0, green: 248/255.0, blue: 253/255.0, alpha: 0.7).cgColor, UIColor(hex: "#FFFFFF").cgColor]
        bgLayer1.locations = [0, 0.34, 1]
        
        let backview = UIView(frame: (AppDelegate.share()?.window!.frame)!)
        view.addSubview(backview)
        bgLayer1.frame = (AppDelegate.share()?.window!.frame)!
        backview.layer.addSublayer(bgLayer1)

        view.sendSubviewToBack(backview)
    }
    
    @IBOutlet weak var privacy: UIButton!
    private var viewModel: LoginViewModel?
    private var account: String = ""
    private var password = ""

    @IBOutlet private weak var accountView: LoginTextView! {
        didSet {
            accountView.delegate = self
            accountView.leftImg = UIImage(named: "login_account")
            accountView.placeholder = "请输入手机号"
            accountView.keyboardType = .numberPad
            accountView.type = .account
            accountView.inputStr = UserDefaults.account.decryptWithAES()
        }
    }
    @IBOutlet private weak var passwordView: LoginTextView! {
        didSet {
            passwordView.delegate = self
            passwordView.leftImg = UIImage(named: "login_password")
            passwordView.placeholder = "请输入登录密码"
            passwordView.type = .password
            passwordView.inputStr = UserDefaults.password.decryptWithAES()
        }
    }
    @IBOutlet private weak var rememberBtn: UIButton! {
        didSet {
            rememberBtn.isSelected = UserDefaults.isRemember
        }
    }
    @IBOutlet private weak var registerBtn: UIButton! {
        didSet {
            registerBtn.setTitleColor(.mainColor, for: .normal)
            registerBtn.setTitleColor(.mainLight, for: .highlighted)
        }
    }
    @IBOutlet private weak var forgetBtn: UIButton! {
        didSet {
            forgetBtn.setTitleColor(.mainColor, for: .normal)
            forgetBtn.setTitleColor(.mainLight, for: .highlighted)
        }
    }
    @IBOutlet private weak var loginButton: UIButton! {
        didSet {
            loginButton.layer.cornerRadius = loginButton.height * 0.5
            loginButton.layer.masksToBounds = true
            loginButton.setBackgroundImage(UIImage(color: .mainGray), for: .disabled)
            loginButton.setBackgroundImage(UIImage(color: .mainColor), for: .normal)
            loginButton.setBackgroundImage(UIImage(color:UIColor.mainColor.withAlphaComponent(0.85)), for: .highlighted)
            loginButton.isEnabled = nextStepEnable
        }
    }
    
    @IBAction func lawAndPrivacyClicked() {
        let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
        agreementView.show(type: .appLawAndPrivacy)
    }
    
    @IBAction func privacyCheck(_ sender: UIButton) {
        sender.isSelected.toggle()
    }
    
    @IBAction private func rememberBtnClicked(_ sender: UIButton) {
        sender.isSelected.toggle()
        UserDefaults.saveIsRemember(sender.isSelected)
    }
    
    @IBAction private func nextStepBtnClicked(_ sender: UIButton) {
        view.endEditing(true)
        if !privacy.isSelected {
            HUDTool.show(message: "请阅读并同意《法律声明及隐私权协议》")
            return
        }
        login()
    }
    
    @IBAction private func register(_ sender: UIButton) {
        let registerNav =  YSGRegisterViewController()
        registerNav.modalPresentationStyle = .fullScreen
        present(registerNav, animated: true, completion: nil)
    }
    
    @IBAction private func forget(_ sender: UIButton) {

        let forgetNav = YSGResetViewController()
        forgetNav.modalPresentationStyle = .fullScreen
        present(forgetNav, animated: true, completion: nil)
//        forgetVc.handlerClosure = { [weak self] in
//            guard let self = self else { return }
//            self.passwordView.inputStr = UserDefaults.password.decryptWithAES()
//        }
    }
    
    @objc private func endEditing() {
        view.endEditing(true)
    }
    
    @objc private func back() {
        dismiss(animated: true, completion: nil)
    }
}

extension LoginViewController: LoginTextViewDelegate {
    func loginBtnIsEnable() {
        loginButton.isEnabled = accountView.isEnable || passwordView.isEnable
    }
    
    private func login() {
        HUDTool.showActivity()
        account = accountView.inputStr.encryptWithAES()
        password = passwordView.inputStr.encryptWithAES()
        LoginViewModel.login(account: account, password: password, success: { model in
            HUDTool.hideActivity()
            let viewModel = LoginViewModel(model: model)
            self.viewModel = viewModel
            viewModel.save(account: self.account, password: self.password)
            self.bindPushDeviceToken()
            MeetingManager.shared.loginSDK()
            WebSocketManager.shared().connect()
            NotificationCenter.default.post(name: NotiName.loginSuccess, object: nil)
            AppDelegate.share()?.setRootVc()
        }) { errorMsg in
            HUDTool.hideActivity()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    private func bindPushDeviceToken() {
        LoginViewModel.bindDeviceTokenForPush(deviceToken: UserDefaults.deviceToken) { errorMsg in
            if errorMsg != nil {
                HUDTool.showError(message: errorMsg)
            }
        }
    }
    
    private func resetRootVc() {
        let mainVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "mainVcId") as! MainViewController
        mainWindow.rootViewController = mainVc
    }
}
